package com.guli.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guli.acl.entity.User;
import com.guli.acl.service.PermissionService;
import com.guli.acl.service.UserService;
import com.guli.security.entity.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ZHAOZHENYU
 * @since 2022/10/6
 * 权限认证整合数据库
 */

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        // 判断用户是否存在
        if (null == user){
            throw new UsernameNotFoundException("用户名不存在！");
        }
        com.guli.security.entity.User secUser = new com.guli.security.entity.User();
        BeanUtils.copyProperties(user,secUser);
        // 查出当前用户所有权限列表
        List<String> authorities = permissionService.selectPermissionValueByUserId(user.getId());
        // 将字符串形式权限放入UserDerail  框架自动将其变成权限SimpleGrantedAuthority
        SecurityUser securityUser = new SecurityUser(secUser);
        securityUser.setPermissionValueList(authorities);
        return securityUser;
    }
}
